import { Button, Form, Modal, Table, Input, Spin } from "antd";
import { useRef, useState } from "react";
import request from "../../framework/common/utils/request";
import qs from "qs";
import { useForm } from "../../framework/common/context/metadata-context";
import useTable from "../../framework/common/lifecycle/useTable";
import message from "../../framework/common/utils/message";

import { openReationProcess } from "./utility";

import { useUpdate } from "ahooks";

export default function ({
    urlPrefix,
    handleOk,
    relationProcessList//已经选择过的流程
}) {
  const [isVisible, setIsVisible] = useState(false);
  function showModal() {
    setIsVisible(true);
  }
  return (
    <>
        <span id="js-relation" className="float-right cursor-pointer" onClick={showModal}>
            <i className="text-sm iconfont icon-tianjia text-color-1990ff"></i> 关联流程
        </span>
      {isVisible 
        && <ModalContent 
            isVisible={isVisible} 
            setIsVisible={setIsVisible} 
            urlPrefix={urlPrefix}
            addRows={handleOk}
            relationProcessList={relationProcessList}
            ></ModalContent>}
    </>
  );
}
const ModalContent = function ({ isVisible, setIsVisible, urlPrefix, addRows, relationProcessList }) {

//   let currentSelectedRowKeys = [];//当前弹出框选择的流程id
  let selectedRowKeys = useRef(
    relationProcessList.map(function(item){
      return item.proc_id;
    })
  )//已经选择过并添加到了已选列表的流程id
  let selectedRows = useRef([]);//缓存列表上选中的流程
  let tableSelectedRowKeys = useRef([]);//缓存列表上选中的流程id
  let updater = useUpdate();

  //弹出框确认按钮事件
  function handleOk() {
    if(selectedRows.current.length <=0 ){
      message.info({
        content: "请选择关联流程"
      })
      return;
    }
    addRows?.(selectedRows.current)
    setIsVisible(false);
  }
  const handleCancel = () => {
    setIsVisible(false);
  };
  const formManager = useForm();
  const [form] = Form.useForm();

  // const { getFieldDecorator } = form;
  const { tableProps, search } = useTable(
    (
      {
        current = 1, // 设定初始在第1页
        pageSize, // 初始每页默认10条数据
        sorter,
      },
      formData
    ) => {
      //搜索时，清空已选数据
      selectedRows.current = [];
      tableSelectedRowKeys.current = [];

      return request({
        url: "/flowinstance/process/get-relation-process",
        method: "post",
        isForm: true,
        data: qs.stringify({
          pageIndex: current,
          pageSize: pageSize,
          processName: formData.keyword || "",
          selected_ids:JSON.stringify(selectedRowKeys.current)//已选择的关联流程
        }),
      }).then(function (response) {
        let list = response?.data?.list || [];
        list.forEach((item, index) => {
          item.index = index + 1 + (current - 1) * pageSize;
        //   item.circulated_user_names && (item.circulated_user_names = item.circulated_user_names.join("、"));
        //   item.CreationTime = item.CreationTime.replace(/(:\d+)$/g, "");
        });
        return {
          total: response.data.total_rows_count,
          list: list,
        };
      });
    },
    {
      form,
    }
  );
  const { submit } = search;
  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      width: 70,
    },
    {
      title: "流程名称",
      dataIndex: "name",
      ellipsis: true,
      render:function(text, record, index){
        return <RelationProcessLink
                  href={record.url_pc}
                  text={text}
                ></RelationProcessLink>
      }
    },
    {
      title: "发起时间",
      dataIndex: "initiater_time",
      width: 180,
      ellipsis: true,
    }
  ];
  
  return (
    <Modal centered={true} title="关联流程" width={760} visible={isVisible} onOk={handleOk} onCancel={handleCancel}>
      <Form form={form}>
        <Form.Item noStyle name="keyword">
          <Input.Search autoComplete="off" placeholder="请输入流程名称" onSearch={submit} style={{ width: 290, marginBottom: "10px" }} />
        </Form.Item>
      </Form>
      <Table 
        className="table-madol"
        columns={columns} 
        scroll={{ y: 360 }} 
        rowKey="proc_id" 
        rowSelection={{
          selectedRowKeys: tableSelectedRowKeys.current,
          columnWidth: 43,
          onChange:function(rowKeys, rows, info){
            tableSelectedRowKeys.current = rowKeys;
            selectedRows.current = rows;//回填已选的关联流程
            updater();
          }
        }}
        {...tableProps} 
      />
    </Modal>
  );
};

//关联流程超链接
function RelationProcessLink({
  href,
  text
}){

  const [spinState, setSpinState] = useState(false);

  return <Spin
            spinning={spinState}
          >
            <a onClick={()=>{
              setSpinState(true);
              openReationProcess({url: href}).then(function(){
                setSpinState(false);
              }).catch(function(){
                setSpinState(false);
              })
            }}>{text}</a>
          </Spin>
}